package com.czk.gulimall.cart.interceptor;

import com.czk.common.constant.AuthServerConstant;
import com.czk.common.vo.MemberResponseVo;
import com.czk.gulimall.cart.constant.CartConstant;
import com.czk.gulimall.cart.vo.UserInfoTo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.UUID;

/**
 * 执行目标方法之前，判断用户的登录状态
 * 并封装给controller
 *
 * @Author:ChenZhangKun
 * @Date: 2022/3/14 21:29
 */
@Component
public class CartInterceptor implements HandlerInterceptor {
    /**
     * 实现用户与登录信息绑定
     */
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // spring-session封装后的request,从redis取数据
        UserInfoTo userInfoTo = new UserInfoTo();

        HttpSession session = request.getSession();
        // 必须保持同个cookie才能获取得到
        MemberResponseVo member = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (member != null) {
            // 登录
            userInfoTo.setUserId(member.getId());
        }
        // 没登录
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (Objects.equals(name, CartConstant.TEMP_USER_COOKIE_NAME)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }
            }
        }
        // 分配user-key
        if (StringUtils.isEmpty(userInfoTo.getUserId())) {
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        threadLocal.set(userInfoTo);
        // 放行
        return true;
    }

    /**
     * 业务执行之后
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //
        UserInfoTo userInfoTo = threadLocal.get();
        // 临时用户
        if (!userInfoTo.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
